package com.example.review;

import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserFactory;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.StringReader;
import java.net.HttpURLConnection;
import java.net.URL;

import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

public class chapterNine3Activity extends AppCompatActivity implements View.OnClickListener {

    TextView responseText;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_chapter_nine3);
        Button sendRequest = (Button) findViewById(R.id.send_request);
        Button okhttp =findViewById(R.id.send_request2);
        responseText = (TextView) findViewById(R.id.response_text);
        sendRequest.setOnClickListener(this);
        okhttp.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        if (v.getId() == R.id.send_request) {
            sendRequestWithHttpURLConnection();
        }else {
            sendRequestWithOkHttpConnection();
        }
    }


    //通过okhttp
    private void sendRequestWithOkHttpConnection(){
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    OkHttpClient okHttpClient=new OkHttpClient();
                    Request request=new Request.Builder().url("http://www.baidu.com").build();
                    Response response = okHttpClient.newCall(request).execute();
                    String responseData = response.body().string();
                    showResponse(responseData);
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }).start();
    }

    //通过httpURL
    private void sendRequestWithHttpURLConnection() {
        // 开启线程来发起网络请求
        new Thread(new Runnable() {
            @Override public void run() {
                HttpURLConnection connection = null;
                BufferedReader reader = null;
                try {
                    URL url = new URL("http://www.baidu.com");
                    connection = (HttpURLConnection) url.openConnection();
                    connection.setRequestMethod("GET");
                    connection.setConnectTimeout(8000);
                    connection.setReadTimeout(8000);
                    //以获取到服务器返回的输入流
                    InputStream in = connection.getInputStream();
                    // 下面对获取到的输入流进行读取
                    reader = new BufferedReader(new InputStreamReader(in));
                    StringBuilder response = new StringBuilder();
                    String line;
                    while ((line = reader.readLine()) != null) {
                        response.append(line);
                    }
                    showResponse(response.toString());
                } catch (Exception e) {
                    e.printStackTrace();
                } finally {
                    if (reader != null) {
                        try {
                            reader.close();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                    if (connection != null) {
                        //关闭连接
                        connection.disconnect();
                    }
                }
            }
        }).start();
    }


    private void showResponse(final String response) {
        //Android是不允许在子线程中进行UI操作的，我们需要 通过这个方法将线程切换到主线程，然后再更新UI元素
        runOnUiThread(new Runnable() {
            @Override public void run() {
                // 在这里进行UI操作，将结果显示到界面上
                responseText.setText(response);
            }
        });
    }


/**
 * 需要解析的数据
 */
//    <apps>
//        <app>
//            <id>1</id>
//            <name>Google Maps</name>
//            <version>1.0</version>
//        </app>
//        <app>
//            <id>2</id>
//            <name>Chrome</name>
//            <version>2.1</version>
//        </app>
//        <app>
//            <id>3</id>
//            <name>Google Play</name>
//            <version>2.3</version>
//        </app>
//    </apps>
    /**
     * Pull解析方式 解析XML数据
     * @param xmlData
     */
    private void parseXMLWithPull(String xmlData) {
        try {
            //先要获取到一个XmlPullParserFactory 的实例，
            // 并借助这个实例得到XmlPullParser 对象，
            // 然后调 用XmlPullParser 的setInput() 方法将服务器返回的XML数据设置进去就可以开始解析 了
            XmlPullParserFactory factory = XmlPullParserFactory.newInstance();
            XmlPullParser xmlPullParser = factory.newPullParser();
            xmlPullParser.setInput(new StringReader(xmlData));
            //开始解析  过getEventType() 可以得到当前的解析事件
            int eventType = xmlPullParser.getEventType();
            String id = "";
            String name = "";
            String version = "";
            //如果当前的解析事件不等于XmlPullParser.END_DOCUMENT，
            // 说 明解析工作还没完成，调用next() 方法后可以获取下一个解析事件
            while (eventType != XmlPullParser.END_DOCUMENT) {
                //得到当前节点的名字
                String nodeName = xmlPullParser.getName();
                switch (eventType) {
                    // 开始解析某个节点  一个app节点
                    case XmlPullParser.START_TAG: {
                        if ("id".equals(nodeName)) {
                            //调用nextText() 方法来获取节点内具体的内容
                            id = xmlPullParser.nextText();
                        } else if ("name".equals(nodeName)) {
                            name = xmlPullParser.nextText();
                        } else if ("version".equals(nodeName)) {
                            version = xmlPullParser.nextText();
                        }break;
                    }
                    // 完成解析某个节点
                    case XmlPullParser.END_TAG: {
                        if ("app".equals(nodeName)) {
                            Log.d("MainActivity", "id is " + id);
                            Log.d("MainActivity", "name is " + name);
                            Log.d("MainActivity", "version is " + version);
                        }
                        break;
                    }
                    default:
                        break;
                }
                //调用next() 方法后可以获取下一个解析事件
                eventType = xmlPullParser.next();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}